<template>
	<view class="marketing-form">
		<view class="content-container">
			<!-- 目标 -->
			<view class="form-section">
				<view class="section-title">阶段目标</view>
				<view class="stage-target-picker">
					<picker @change="onStageTargetChange" :value="stageTargetIndex" :range="stageTargetOptions"
						range-key="goalName">
						<view class="picker-view">
							{{ stageTargetIndex !== -1 && stageTargetOptions[stageTargetIndex] ? stageTargetOptions[stageTargetIndex].goalName : '请选择阶段目标' }}
							<uni-icons type="down" size="24" color="#999" class="picker-icon"></uni-icons>
						</view>
					</picker>
				</view>
			</view>


			<!-- 营销方式 -->
			<view class="form-section">
				<view class="section-title">营销方式 </view>
				<view class="marketing-methods">
					<view class="method-item" v-for="(item, index) in marketingMethods" :key="index"
						@click="selectMethod(item)" :class="{ 'selected': formData.marketingMethod === item.value }">
						<uni-icons :type="item.icon" color="rgb(238 201 0)" size="28"></uni-icons>
						<text class="method-name">{{ item.name }}</text>
					</view>
				</view>
			</view>

			<!-- 营销结果 -->
			<view class="form-section">
				<view class="section-title">营销结果</view>
				<view class="result-options j-s-b">
					<radio-group @change="radioChange" color="#e60012" class="option-item width-100 j-s-b">
						<label class="uni-list-cell uni-list-cell-pd" v-for="(item, index) in resultOptions"
							:key="item.value">
							<view>
								<radio color="#e60012" :value="item.value"
									:checked="item.value == formData.marketingResult" />
							</view>
							<view class="option-text">{{item.name}}</view>
						</label>
					</radio-group>
				</view>
				<view class="reject-reason">
					<view class="desc-title">
						描述
					</view>
					<textarea v-model="formData.rejectReason" placeholder="请输入描述"
						placeholder-style="color:#999"></textarea>
				</view>
			</view>

			<!-- 意向产品 -->
			<!-- 意向产品（修改后：单选） -->
			<view class="form-section">
				<view class="section-title">意向产品</view>
				<!-- 1. 组件替换：checkbox-group → radio-group -->
				<radio-group @change="radioProductChange" color="#e60012">
					<view class="product-options">
						<label class="option-item" v-for="(item, index) in productOptions" :key="index">
							<!-- 2. 选项组件替换：checkbox → radio -->
							<radio color="#e60012" :value="item.value"
								:checked="formData.intentProduct === item.value" />
							<text class="option-text">{{ item.name }}</text>
						</label>
					</view>
				</radio-group>
			</view>

			<!-- 营销成果 -->
			<view class="form-section">
				<view class="section-title">营销成果</view>
				<view class="achievement-fields">
					<view class="field-item">
						<text class="field-label">产品名称：</text>
						<input v-model="formData.productName" placeholder="请输入" placeholder-style="color:#999" />
					</view>
					<view class="field-item">
						<text class="field-label">达成数量：</text>
						<input v-model.number="formData.achievementAmount" type="number" placeholder="请输入达成数量"
							placeholder-style="color:#999" />
						<text class="unit-text">{{unit}}</text>
					</view>
				</view>
			</view>

			<!-- 营销凭证 -->
			<view class="form-section">
				<view class="section-title">营销凭证</view>
				<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
					:maxCount="10"></u-upload>
			</view>

			<!-- 保存按钮 -->
			<button class="save-btn" @click="submitForm">保存</button>
		</view>
	</view>
</template>

<script>
	import {
		http,
		API_BASE_URL
	} from '@/common/http.js';
	import {
		addKmhProgress,
		selectNewPhaseGoal
	} from '@/common/api/renwu.js'
	export default {
		data() {
			return {
				fileList1: [],
				formData: {
					stageTarget: '', //阶段目标
					marketingMethod: '', // 选中的营销方式值
					marketingResult: '', // 营销结果值
					rejectReason: '', // 拒绝原因
					intentProduct: '', // 选中的意向产品值（单选）
					productName: '', // 产品名称
					achievementAmount: '', // 达成金额
					certificates: [] // 上传的凭证图片地址数组
				},
				unit: '',
				// 新增：阶段目标相关数据
				stageTargetOptions: [],
				stageTargetIndex: -1, // 选中的索引（默认未选择）
				marketingMethods: [{
						name: '文字记录',
						value: 1,
						icon: 'compose'
					},
					{
						name: '上门拜访',
						value: 2,
						icon: 'home'
					},
					{
						name: '发微信',
						value: 3,
						icon: 'weixin'
					},
					{
						name: '打电话',
						value: 4,
						icon: 'phone'
					},
					{
						name: '二维码预约',
						value: 5,
						icon: 'scan'
					},
					{
						name: '发短信',
						value: 6,
						icon: 'chatboxes'
					},
					{
						name: '网点面谈',
						value: 7,
						icon: 'navigate'
					}
				],
				resultOptions: [{
						name: '预约成功',
						value: '1',
						disabled: false
					},
					{
						name: '拒绝',
						value: '2',
						disabled: false
					},
					{
						name: '成交',
						value: '3',
						disabled: false
					}
				],
				productOptions: [{
						name: '存款',
						value: 1
					},
					{
						name: '贷款',
						value: 2
					},
					{
						name: '保险',
						value: 3
					},
					{
						name: '收单',
						value: 4
					},
					{
						name: '贵金属',
						value: 5
					},
					{
						name: '其他',
						value: 6
					}
				],
				step_id: '',
				customerId: '',
				task_id: '',

			};
		},
		onLoad(options) {
			this.step_id = options.step_id
			this.customerId = options.customer_id
			this.task_id = options.task_id
			this.getStep(options.step_id)
		},
		methods: {
			// 阶段目标
			getStep(id) {
				selectNewPhaseGoal({
					id
				}).then(res => {
					console.log(res, '---阶段目标')
					this.stageTargetOptions = res.data
				})
			},
			// 新增：阶段目标选择事件
			onStageTargetChange(e) {
				console.log(e, '--------')
				const index = e.detail.value;
				this.stageTargetIndex = index;
				// 将选中的value同步到formData
				this.formData.stageTarget = this.stageTargetOptions[index].id;
				this.unit = this.stageTargetOptions[index].unit;
			},

			// 营销成功
			radioChange(e) {
				console.log(e, '-----')
				this.formData.marketingResult = e.detail.value
			},
			navigateBack() {
				uni.navigateBack();
			},
			selectMethod(method) {
				this.formData.marketingMethod = method.value;
			},
			// checkboxChange(e) {
			// 	console.log(e, '----')
			// 	this.formData.intentProducts = e.detail.value
			// },
			// 1. 新增：意向产品单选事件（替换原 checkboxChange）
			radioProductChange(e) {
				console.log("选中的意向产品：", e.detail.value);
				this.formData.intentProduct = e.detail.value; // 直接赋值字符串
			},

			async submitForm() {
				if (this.stageTargetIndex === -1) {
					uni.showToast({
						title: '请选择阶段目标',
						icon: 'none'
					});
					return;
				}
				if (!this.formData.marketingMethod) {
					uni.showToast({
						title: '请选择营销方式',
						icon: 'none'
					});
					return;
				}
				if (!this.formData.marketingResult) {
					uni.showToast({
						title: '请选择营销结果',
						icon: 'none'
					});
					return;
				}
				// if (this.formData.intentProducts.length <= 0) {
				// 	uni.showToast({
				// 		title: '请选择意向产品',
				// 		icon: 'none'
				// 	});
				// 	return;
				// }
				// 意向产品验证：从“数组长度≤0”改为“字符串为空”
				if (!this.formData.intentProduct) {
					uni.showToast({
						title: '请选择意向产品',
						icon: 'none'
					});
					return;
				}
				if ((this.formData.marketingResult == 3 && !this.formData.productName) || (this.formData
						.intentProduct == 6 && !this.formData.productName)) { // 选其他类型
					uni.showToast({
						title: '请输入产品名称',
						icon: 'none'
					});
					return;
				}
				if ((this.formData.marketingResult == 3 && !this.formData.achievementAmount) || (this.formData
						.intentProduct == 6 && !this.formData.achievementAmount)) {
					uni.showToast({
						title: '请输入达成数量',
						icon: 'none'
					});
					return;
				}
				if ((this.formData.marketingResult == 3 && this.fileList1.length <= 0) || (this.formData
						.intentProduct == 6 && this.fileList1.length <= 0)) {
					uni.showToast({
						title: '请上传凭证',
						icon: 'none'
					});
					return;
				}

				// 模拟提交到服务器，实际可替换为uni.request调用后端接口
				console.log('表单数据提交：', this.formData);
				uni.showLoading({
					title: '提交中...'
				});
				let img = this.fileList1.map(item => item.url)
				let params = {
					taskId: this.task_id,
					phaseTaskId: this.step_id,
					phaseGoal: this.formData.stageTarget, //阶段目标id
					customerId: this.customerId,
					way: this.formData.marketingMethod,
					result: this.formData.marketingResult,
					description: this.formData.rejectReason,
					intentionProduct: this.formData.intentProduct,
					productName: this.formData.productName,
					count: this.formData.achievementAmount,
					url: img.join(',')
				}
				try {
					let res = await addKmhProgress(params)
					uni.hideLoading();
					uni.showToast({
						title: '提交成功',
						icon: 'success'
					});
					setTimeout(() => {
						uni.navigateBack()
					}, 1300);
				} catch (error) {
					//TODO handle the exception
				}

			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1);
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this[`fileList${event.name}`].length;
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: "uploading",
						message: "上传中",
					});
				});
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url);
					let item = this[`fileList${event.name}`][fileListLen];
					this[`fileList${event.name}`].splice(
						fileListLen,
						1,
						Object.assign(item, {
							status: "success",
							message: "",
							url: result,
						})
					);
					fileListLen++;
				}
			},

			async uploadFilePromise(url) {
				console.log('上传中')
				try {
					uni.showLoading({
						title: '上传中...'
					});
					const res = await http.upload('/wx/performance/addEvidence', url);
					console.log('图片上传结果：', res);
					return res; // 返回图片URL
				} catch (err) {
					console.error('上传失败：', err);
				}
			},
		}
	};
</script>

<style scoped>
	.marketing-form {
		width: 100%;
		min-height: 100vh;
		background-color: #f5f5f5;
	}

	/* 导航栏样式 */
	.navbar {
		height: 88rpx;
		background-color: #e60012;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 32rpx;
	}

	.nav-title {
		color: #fff;
		font-size: 32rpx;
	}

	/* 表单区块样式 */
	.form-section {
		padding: 24rpx 32rpx;
		background-color: #fff;
		margin-bottom: 20rpx;
	}

	.section-title {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 20rpx;
		padding: 8rpx 0;
		/* border-bottom: 1px solid #eee; */
		position: relative;
		/* 父元素相对定位 */
		padding-left: 16px;
		/* 预留竖线空间 */
	}

	.xing {
		color: red;
	}

	.section-title::before {
		content: '';
		position: absolute;
		left: 0;
		/* 左侧对齐 */
		top: 50%;
		transform: translateY(-50%);
		/* 垂直居中 */
		width: 3px;
		/* 竖线宽度 */
		height: 80%;
		/* 竖线高度（可调整为固定值如30px） */
		background-color: #e60012;
		/* 竖线颜色 */
	}

	/* 营销方式样式 */
	.marketing-methods {
		display: flex;
		flex-wrap: wrap;
		gap: 24rpx;
	}

	.method-item {
		width: 22%;
		display: flex;
		flex-direction: column;
		align-items: center;
		cursor: pointer;
	}

	.method-item .uni-icons {
		background-color: #e60012;
		border-radius: 50%;
		padding: 8rpx;
		margin-bottom: 4rpx;
		border: 4rpx solid #fff;
	}

	.selected .uni-icons {
		border: 4rpx solid #FFD700;

	}

	.method-name {
		font-size: 24rpx;
		color: #666;
	}

	.selected {
		color: #e60012;
	}

	.selected uni-icons {
		color: #e60012;
	}

	.selected .method-name {
		color: #e60012;
		font-weight: bold;
	}

	.desc-title {
		font-size: 24rpx;
		margin-bottom: 8rpx;
	}

	/* 选项样式 */
	.result-options,
	.product-options {
		width: 100%;
		display: flex;
		flex-wrap: wrap;
		gap: 24rpx;
		margin-bottom: 20rpx;
	}

	.option-item {
		display: flex;
		align-items: center;
	}

	.uni-list-cell {
		display: flex;
		align-items: center;
		margin-right: 16rpx;
		justify-content: space-between;
	}

	.option-text {
		font-size: 24rpx;
		color: #666;
		/* margin-left: 8rpx; */
	}

	/* 拒绝原因输入框 */
	.reject-reason textarea {
		width: 100%;
		min-height: 160rpx;
		padding: 16rpx;
		border: 1px solid #eee;
		border-radius: 8rpx;
		box-sizing: border-box;
		font-size: 24rpx;
	}

	/* 成果字段样式 */
	.achievement-fields {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.field-item {
		display: flex;
		align-items: center;
	}

	.field-label {
		font-size: 24rpx;
		color: #666;
		width: 120rpx;
	}

	.field-item input {
		flex: 1;
		padding: 16rpx;
		border: 1px solid #eee;
		border-radius: 8rpx;
		/* box-sizing: border-box; */
		font-size: 24rpx;
	}

	.unit-text {
		font-size: 24rpx;
		color: #999;
		margin-left: 8rpx;
	}

	/* 凭证上传样式 */
	.certificate-upload {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		width: 100%;
		height: 160rpx;
		border: 1px dashed #eee;
		border-radius: 8rpx;
		margin-bottom: 20rpx;
	}

	.upload-text {
		font-size: 24rpx;
		color: #999;
		margin-top: 8rpx;
	}

	.certificate-img {
		width: 100%;
		height: 200rpx;
		margin-bottom: 12rpx;
		border-radius: 8rpx;
	}

	/* 保存按钮 */
	/* 	.save-btn {
		background-color: #e60012;
		color: #fff;
		font-size: 28rpx;
		width: 60%;
		margin: 32rpx auto;
		border-radius: 40rpx;
	} */

	.marketing-form {
		width: 100%;
		min-height: 100vh;
		background-color: #f5f5f5;
		/* 相对定位，作为按钮的定位参考 */
		position: relative;
	}

	/* 内容容器 - 添加底部内边距，避免最后一部分内容被按钮遮挡 */
	.content-container {
		padding-bottom: 120rpx;
		/* 底部预留足够空间给按钮 */
	}

	/* 其他原有样式不变... */

	/* 保存按钮 - 固定在底部 */
	.save-btn {
		background-color: #e60012;
		color: #fff;
		font-size: 28rpx;
		width: 60%;
		margin: 0 auto;
		border-radius: 40rpx;
		height: 80rpx;
		/* 适当增加高度 */
		line-height: 80rpx;
		/* 文字垂直居中 */

		/* 固定定位 */
		position: fixed;
		bottom: 30rpx;
		/* 距离底部的距离 */
		left: 0;
		right: 0;
		z-index: 99;
		/* 确保在内容上方 */
	}

	/* 阶段目标选择框样式 */
	.stage-target-picker {
		width: 100%;
		/* padding: 0 16rpx; */
	}

	.picker-view {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 80rpx;
		background-color: #f9f9f9;
		border-radius: 8rpx;
		padding: 0 20rpx;
		font-size: 26rpx;
		color: #333;
	}

	.picker-icon {
		margin-left: 10rpx;
	}
</style>